package br.com.gerenciador_recursos.servlets.util;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.gerenciador_recursos.model.User;
import br.com.gerenciador_recursos.model.UserType;
import br.com.gerenciador_recursos.service.UserLocalServiceUtil;
import br.com.gerenciador_recursos.util.Constants;
import br.com.gerenciador_recursos.util.ParamUtil;

public class UserActionUtil {

	public static User addOrUpdate(HttpServletRequest req,
			HttpServletResponse res, boolean inserir) throws Exception {

		int userId = ParamUtil.getInt(req, Constants.USER_ID);

		String screenName = ParamUtil.getString(req, Constants.SCREEN_NAME);

		String firstName = ParamUtil.getString(req, Constants.FIRST_NAME);

		String lastName = ParamUtil.getString(req, Constants.LAST_NAME);

		String emailAddress = ParamUtil.getString(req, Constants.EMAIL_ADDRESS);

		String password = ParamUtil.getString(req, Constants.PASSWORD);

		String[] userTypesArray = ParamUtil.getStringValues(req,
				Constants.USER_TYPES);

		Set<UserType> userTypes = new HashSet<UserType>(userTypesArray.length);

		for (String userTypeStr : userTypesArray) {
			userTypes.add(UserType.valueOf(userTypeStr));
		}

		User user = null;

		if (inserir) {
			user = UserLocalServiceUtil.add(screenName, firstName, lastName,
					emailAddress, password, userTypes);

		} else {
			user = UserLocalServiceUtil.update(userId, screenName, firstName,
					lastName, emailAddress, password, userTypes);
		}

		return user;
	}

	public static void delete(HttpServletRequest req, HttpServletResponse res)
			throws Exception {

		int userId = ParamUtil.getInt(Constants.USER_ID);

		UserLocalServiceUtil.delete(userId);
	}

}
